package com.focusai.efairy.ui.fragment;

import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.focusai.efairy.R;
import com.focusai.efairy.model.dev.DeviceItem;
import com.focusai.efairy.model.msg.MsgItem;
import com.focusai.efairy.ui.activity.dev.DevChattingActivity;
import com.focusai.efairy.ui.adapter.NewsAdapter;
import com.focusai.efairy.ui.adapter.base.BaseRecyclerAdapter;
import com.focusai.efairy.ui.adapter.base.BaseRecyclerViewHolder;
import com.focusai.efairy.ui.adapter.msg.DeviceConversation;
import com.focusai.efairy.ui.base.BaseFragment;
import com.focusai.efairy.ui.widget.TitleView;
import com.focusai.efairy.utils.GsonHelper;
import com.focusai.efairy.utils.log.Log;

import java.util.ArrayList;
import java.util.List;

import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.message.TextMessage;
import io.rong.push.RongPushClient;
import io.rong.push.common.RongException;

/**
 * Created by luo_guangwen on 2017/7/11.
 */

public class NewFragment extends BaseFragment implements View.OnClickListener {
    private static final String TAG = NewFragment.class.getName();
    public static final int REQUEST_CHATTING_CODE = 0x10;

    private RecyclerView mRecylerView;
    private NewsAdapter mAdapter;
    private SwipeRefreshLayout swipeRefreshLayout;
    private View tipView;
    private TextView titleRightText;
    private TextView textAllRead;
    private RelativeLayout rl_buttom_view;
    private boolean isSetRongIMClientListener = false;
    private boolean refreshPushData = true;

    public NewFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_msg, container, false);
        initView(view);
        try {
            RongPushClient.checkManifest(getActivity().getApplicationContext());
        } catch (RongException e) {
            e.printStackTrace();
        }
        setDefaultValues();
        loadData();
        return view;
    }

    @Override
    protected void initView(View view) {
        mRecylerView = findView(view, R.id.msg_rcyc_view);
        swipeRefreshLayout = findView(view, R.id.layout_refresh);
        rl_buttom_view = findView(view, R.id.rl_buttom_view);
        tipView = findView(view, R.id.iv_no_data);
        TitleView titleView = findView(view, R.id.title_view);
        titleRightText = titleView.getmTextRight();
        textAllRead = findView(view, R.id.tv_all_read);
        textAllRead.setOnClickListener(this);
        findView(view, R.id.tv_delete).setOnClickListener(this);
    }

    @Override
    protected void setDefaultValues() {
        mAdapter = new NewsAdapter(getActivity());
        mRecylerView.setAdapter(mAdapter);
        mRecylerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loadData();
            }
        });
        mAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseRecyclerViewHolder holder) {
                if (holder == null) return;
                int position = mRecylerView.getChildLayoutPosition(holder.itemView);
                DeviceConversation conversation = mAdapter.getData().get(position);
                String deviceId = conversation.conversation.getTargetId().replace("device_", "");
                if (!isEditMode()) {
                    conversation.isSeleted = !conversation.isSeleted;
                    mAdapter.notifyDataSetChanged();
                    if (getSelectList().size() == 0){
                        textAllRead.setText(R.string.all_readed);
                    }else {
                        textAllRead.setText(R.string.readed);
                    }
                } else {
                    DeviceItem deviceItem = new DeviceItem();
                    deviceItem.efairydevice_id = Long.valueOf(deviceId);
                    deviceItem.efairydevice_name = conversation.msgItem.efairydevice_name;
//                ActivityUtils.startChattingActivity(getActivity(),REQUEST_CHATTING_CODE,deviceItem);
                    Intent intent = new Intent(getActivity(), DevChattingActivity.class);
                    intent.putExtra(DevChattingActivity.KEY_DEV_ITEM, deviceItem);
                    startActivity(intent);
                }
            }
        });
        titleRightText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isEditMode()) {
                    titleRightText.setText(R.string.cancal);
                    textAllRead.setText(R.string.all_readed);
                    rl_buttom_view.setVisibility(View.VISIBLE);
                    mAdapter.setEdit(true);
                    mAdapter.notifyDataSetChanged();
                } else {
                    reSetDataChange();
                }
            }
        });
    }


    @Override
    public void onPause() {
        refreshPushData = false;
        super.onPause();
    }

    @Override
    public void onResume() {
        isSetRongIMClientListener = false;
        refreshPushData = true;
        loadData();
        super.onResume();
    }

    public void setRongIMClientListener() {

        RongIMClient.setOnReceiveMessageListener(new RongIMClient.OnReceiveMessageListener() {
            @Override
            public boolean onReceived(Message message, int j) {
//                List<DeviceConversation> list = new ArrayList<>();
//                TextMessage textMessage = (TextMessage) message.getContent();
//                if (textMessage != null) {
//                    MsgItem msgItem = GsonHelper.getInstance().fromJson(textMessage.getExtra(), MsgItem.class);
//                    DeviceConversation deviceConversation = new DeviceConversation();
//                    deviceConversation.conversation =  new Conversation();
//                    deviceConversation.conversation.setSentTime(message.getSentTime());
//                    deviceConversation.msgItem = msgItem;
//                    list.add(deviceConversation);
//                }
                if(j == 0){
                    refreshPushData();
                }
                return false;
            }
        });
    }


    private void refreshPushData(){
        if(refreshPushData){
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Log.D("refreshPushData","=========刷新消息==========");
                    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                    Ringtone r = RingtoneManager.getRingtone(getActivity().getApplicationContext(), notification);
                    r.play();
                    loadData();
                }
            });
        }
    }


    @Override
    public void onStop() {
        isSetRongIMClientListener = false;
        refreshPushData = false;
        super.onStop();
    }

    private void loadData() {
        RongIMClient.getInstance().getConversationList(new RongIMClient.ResultCallback<List<Conversation>>() {
            @Override
            public void onSuccess(List<Conversation> conversations) {
                if (conversations != null) {
                    List<DeviceConversation> list = new ArrayList<>();
                    Log.D(TAG, conversations.get(0).getConversationTitle());
                    for (Conversation conversation : conversations) {
                        TextMessage textMessage = (TextMessage) conversation.getLatestMessage();
                        MsgItem msgItem = GsonHelper.getInstance().fromJson(textMessage.getExtra(), MsgItem.class);
                        DeviceConversation deviceConversation = new DeviceConversation();
                        deviceConversation.conversation = conversation;
                        deviceConversation.msgItem = msgItem;
                        list.add(deviceConversation);
                    }
                    mAdapter.refreshData(list);
                }
                showTip();
                swipeRefreshLayout.setRefreshing(false);

                if(!isSetRongIMClientListener){
                    setRongIMClientListener();
                    isSetRongIMClientListener = true;
                }

            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
                swipeRefreshLayout.setRefreshing(false);
                showTip();
            }
        }, Conversation.ConversationType.PRIVATE);
    }

    private void showTip() {
        if (mAdapter.getData() != null && mAdapter.getData().size() > 0) {
            tipView.setVisibility(View.GONE);
        } else {
            tipView.setVisibility(View.VISIBLE);
        }
    }

    private boolean isEditMode() {
        return getString(R.string.edit).equals(titleRightText.getText().toString());
    }

    @Override
    public void onClick(View v) {
        List<DeviceConversation> selectList;
        switch (v.getId()) {
            case R.id.tv_all_read:
                selectList = getSelectList();
                if (selectList.size() == 0 && mAdapter.getData() != null){
                    selectList = mAdapter.getData();
                }
                for (DeviceConversation item : selectList) {
                    RongIMClient.getInstance().clearMessagesUnreadStatus(Conversation.ConversationType.PRIVATE,
                            item.conversation.getTargetId(), null);
                }
                reSetDataChange();
                break;
            case R.id.tv_delete:
                selectList = getSelectList();
                if (selectList.size() == 0){
                    showToast("请选择要删除的会话");
                    break;
                }
                for (DeviceConversation item : selectList) {
                    RongIMClient.getInstance().removeConversation(Conversation.ConversationType.PRIVATE,
                            item.conversation.getTargetId(), null);
                    mAdapter.getData().remove(item);
                }
                reSetDataChange();
                break;
            default:
                break;
        }
    }

    private void reSetDataChange() {
        titleRightText.setText(R.string.edit);
        rl_buttom_view.setVisibility(View.GONE);
        List<DeviceConversation> list = mAdapter.getData();
        if (list != null) {
            for (DeviceConversation item : list) {
                item.isSeleted = false;
            }
        }
        mAdapter.setEdit(false);
        mAdapter.notifyDataSetChanged();
        showTip();
    }

    private List<DeviceConversation> getSelectList() {
        List<DeviceConversation> selectList = new ArrayList<>();
        List<DeviceConversation> list = mAdapter.getData();
        if (list != null) {
            for (DeviceConversation item : list) {
                if (item.isSeleted) {
                    selectList.add(item);
                }
            }
        }
        return selectList;
    }

    @Override
    public void onDestroy() {
        RongIMClient.setOnReceiveMessageListener(null);
        super.onDestroy();
    }
}
